import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actions } from '../action/action';
import { Button, Form, Input, InputNumber, Icon, Select, Spin, Modal, Upload, message, Card, Tag } from 'antd';
import { getUploadParam, uploadCDN, validFileType } from '../../qiniu/uploadCDN.js';
import { merge } from '../../helper/helper'
import { doAjaxPost } from '../../common/fetch-ajax'

const FormItem = Form.Item;
const Option = Select.Option;

message.config({
    top: 200,
    duration: 3,
});


// 新增VIP
class NewContact extends Component {

    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, contact) => {
            
            if (!err) {
                var self = this;
                var { filedata, renderdata } = this.props;

                if(renderdata.imgUrl && renderdata.goodsList) {
                    getUploadParam(function (token) {
                        if (token) {
                            var uploadParam = {
                                key: `${Date.now()}.${filedata.fileType}`,
                                token
                            }
                            uploadCDN(filedata.fileEnity, uploadParam, function (res) {
                                res = JSON.parse(res);
                                if (res.key.split('.')[1]) {
                                    self.submitAll(uploadParam.key, `http://p1az9gcpw.bkt.clouddn.com/${uploadParam.key}`);
                                }
                                if(self.props.renderdata.goodsList.length > 0){
                                    let i;
                                    for(i=0; i<self.props.renderdata.goodsList.length; i++){
                                        self.props.renderdata.goodsList[i] = self.props.renderdata.goodsList[i].toString();
                                    }
                                    Object.assign(self.props.renderdata, contact);
                                    // merge( this.props.renderdata, contact);
                                    let data = {
                                        data: self.props.renderdata,
                                        filter: self.props.openStu
                                    }

                                    self.props.addData(data);
                                }else{
                                    message.error("商品不能为空!")
                                }

                            })
                        }
                    })
                }else{
                    message.error('表单数据不完整');
                }
            }
        });
    }

    getVal(val){
        this.props.renderdata.goodsList = val;
    }

    changeHeadortrait(e) {
        var self = this,
            reader = new FileReader(),
            file = e.target.files[0],
            type = file.type.split('/'),
            isTypeValid = validFileType(type[1], ['jpg', 'png', 'jpeg']);
        if (isTypeValid) {
            reader.onload = function () {
                self.props.changePicture({ fileEnity: file, fileUrl: this.result, fileType: type[1] });
            }
            reader.readAsDataURL(e.target.files[0])
        }
    }

    submitAll(image_key, image_url) {
        this.props.submitPics(image_url);
    }

    render() {
        const { renderdata, newContact, triggerNewContact, triggerGoodsDetail } = this.props;
        const { getFieldDecorator } = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
        };

        return (
            <Modal title="新增活动" visible={newContact.isAddContact} onCancel={triggerNewContact} footer={[
                <Button key="back" size="large" onClick={triggerNewContact}  >
                    取消
                </Button>,
                <Button key="submit" type="primary" size="large" onClick={ this.handleSubmit.bind(this)} loading={newContact.loading}>
                    确认
                </Button>,
            ]} >
                <Form>
                    <FormItem
                        {...formItemLayout}
                        label="活动类型"
                        hasFeedback
                    >
                        {
                            getFieldDecorator('type', {
                                initialValue: renderdata.type.toString(),
                                rules: [{ required: true, message: '请选择活动类型!' }],
                            })(<Select placeholder="Please select" style={{ width: 120 }} >
                                <Option key="1" value="1">启动海报</Option>
                                <Option key="2" value="2">店长推荐</Option>
                                <Option key="3" value="3">优惠促销</Option>
                                <Option key="4" value="4">最新商品</Option>
                            </Select>)
                        }
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="活动名称"
                        hasFeedback
                    >
                        {
                            getFieldDecorator('name', {
                                initialValue: renderdata.name,
                                rules: [{ required: true, message: '该字段不能为空!' }],
                            })(<Input />)
                        }
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="图片"
                        hasFeedback
                    >

                            <div className="form-group">
                                <div className="file">
                                    <input  type="file" multiple="multiple" onChange={this.changeHeadortrait.bind(this)}/>
                                </div>
                                <img src={renderdata.imgUrl} />
                            </div>

                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="商品"
                    >
                        <div className="global-search-wrapper ant-card-div" style={{width: 300}}>
                            <a href="#" onClick={triggerGoodsDetail}>编辑商品</a>
                        </div>
                    </FormItem>

                </Form>
            </Modal>
        );
    }
}
const WrapperNewContact = Form.create({})(NewContact);


const _NewContact = connect(
    state => {
        return {
            openStu: state.openStu,
            renderdata: state.renderdata,
            newContact: state.newContact,
            goodslist: state.goodslist,
            goodsIdList: state.goodsIdList,
            filedata: state.filedata
        }
    },
    dispatch => {
        return {
            handleChange:(val) => {
                if(val){
                    const params = {
                        data:{
                            storeNo: user.storeNo,
                            goodsName: val
                        }
                    }
                    actions.getGoodslist(dispatch, params);
                }
            },
            mergeGoodlist:(data, ids) =>{
                dispatch({
                    type: 'render-form-goodslist',
                    val: data

                })
                dispatch({
                    type: 'init-form-goodslist',
                    val: ids

                })
            },
            addData: (contact) => {
                actions.addData(dispatch, contact, (data) => {
                    if (data.success) {
                        dispatch({
                            type: 'close-sdd-contact'
                        });
                        message.success(data.message);
                        setTimeout( ()=>{
                            location.reload();
                        }, 1500)

                    } else {
                        message.error(data.message);
                    }
                })

            },
            renderData: (id) => {
                const params = {
                    id,
                    filter: 'edit'
                }
                actions.renderData(dispatch, params, (data) => {
                    if (data.success) {
                        message.success(data.message);
                    } else {
                        message.error(data.message);
                    }
                })

            },
            changePicture: (param) => {
                dispatch({
                    type: 'set-active-imgurl',
                    val: param
                });
            },
            submitPics: (param) =>{
                dispatch({
                    type: 'set-active-qiniu-imgurl',
                    val: param
                });
            },
            triggerGoodsDetail: () => {
                dispatch({
                    type: 'trigger-goodsDetail-layer'
                });
            }
        }
    }
)(WrapperNewContact);

export default _NewContact;


